/**
 * install - Image installation utility
 */

require( [
'oj/os',
'oj/file',
'oj/term',
'oj/element'
], function (os, file, term, element) {
    'use strict';
    
    var out,
        files = [
            '/install/oj/perf.js',
            '/install/oj/element.js',
            '/install/oj/math.js',
            '/install/oj/remote.js',
            '/install/oj/javascript.js',
            '/install/oj/doc.js',
            '/install/oj/os.js',
            '/install/oj/file.js',
            '/install/oj/term.js',
            '/install/oj/ji.js',
            '/install/oj/ice.js',
            '/install/index.html',
            '/install/oj/gamelib.js',
            '/install/oj/box2d.js',
            '/install/oj/three.js'
        ];


    function read(path, fn) {
        /**
         * Reads a static file from current host.
         */

        var xhr = new XMLHttpRequest();
        xhr.open('GET', path);
        xhr.onreadystatechange = function () {
            if (typeof fn !== 'undefined' && this.status === 200 && this.readyState === 4) {
                fn(this.responseText);
            }
        };
        xhr.send();
    }


    function finalise() {
        /**
         * Ends the installation with a nice message.
         */

        out.print('installation complete');
        out.print(element.create('a', {href: '/?oj/term'}, ['start']));
    }


    function installFile(path) {
        out.print(path + '...');
        read(path, function (m) {
            var dst = file.open(path.replace('/install', ''));
            dst.write(m);
            dst.close(function (m) {
                if (m.hasOwnProperty('error')) {
                    return out.print(m);
                } else if (m.hasOwnProperty('success')) {
                    out.print('installed');
                    if (files.length > 0) {
                        installFile(files.shift());
                    } else {
                        finalise();
                    }
                }
            });
        });
    }


    function install() {
        os.mkdir('/oj', function () {
            os.mkdir('/oj/doc', function () {
                installFile(files.shift());
            });
        });
    }
    
    
    element.create(document.head, 'syle', {'type': 'text/css'}, [
        'html {',
        '  height: 100%;',
        '}',
        'body {',
        '  height: 100%;',
        '}'
    ]);
    
    
    os.identity(document.location, function (m) {
        if (m.hasOwnProperty('login')) {
            document.location = m.login;
            return;
        }
        out = (new term.Term).init(document.body);
        os.environ.user = m;
        out.print('oj ' + oj.version + ' installation');
        os.listdir('/', function (m) {
            if (m.hasOwnProperty('error') && m.error.indexOf('/: No such') === 0) {
                out.print('no previous installation found');
                os.system('/', ['Z/'], function (m) {
                    if (m.hasOwnProperty('error')) {
                        return out.print(m);
                    }
                    out.print('format successful');
                    install();
                });
            } else {
                out.print('previous installation found, skipping format');
                install();
            }
        });
    });

});
